package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.PositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.equipFacility.OhPlanDraftDTO;
import com.xidian.zhiancloud.dto.equipFacility.RepairObjects;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.PositionList;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.equipFacility.OhPlanDraftQO;
import com.xidian.zhiancloud.vo.equipFacility.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description: 检修计划制定
 * @Author: 任启亮
 * @Date: 2020/11/11
 */
@Service
public class OhPlanDraftService {

    private static int count = 0;
    private static Date date = new Date();

    @Autowired
    private OhPlanDraftMapper ohPlanDraftMapper;

    @Autowired
    private OhObjectMapper ohObjectMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private EqFacMngMapper eqFacMngMapper;

    @Autowired
    private PositionMapper positionMapper;

    /**
     * 添加【检修计划制定】
     * @param ohPlanDraftDTO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean add(OhPlanDraftDTO ohPlanDraftDTO) {

        Date temp = new Date();

        if(count == 0){
            date = temp;
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date);
        cal2.setTime(temp);

        if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
                cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)){
            count++;
        }else{
            count = 1;
        }

        //设置检修计划编号
        String str =cal1.get(Calendar.YEAR) + String.format("%02d",cal1.get(Calendar.MONTH)+1) +
                String.format("%02d",cal1.get(Calendar.DAY_OF_MONTH)) + String.format("%06d", count);

        OhPlanDraft ohPlanDraft = ohPlanDraftDTO.getOhPlanDraft();
        OhPlanDraft planDraft = new OhPlanDraft();
        BeanUtils.copyProperties(ohPlanDraft,planDraft);
        planDraft.setProgramNo(str);

        //保存检修人姓名
        String objectsName = "";

        List<RepairObjects> repairObjects = ohPlanDraftDTO.getRepairObjects();
        Set<String> set = new HashSet<>();

        for (RepairObjects object : repairObjects) {

            List<SysUser> users = object.getRepairUsers();
            for (SysUser user : users) {
                SysUser sysUser = sysUserMapper.selectById(user.getId());
                if(sysUser != null){
                    if(!set.contains(sysUser.getName())){
                        set.add(sysUser.getName());
                        objectsName += sysUser.getName() + ",";
                    }
                }
            }
        }

        planDraft.setObjectsName(objectsName);

        //插入检修计划
        int insert = ohPlanDraftMapper.insert(planDraft);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        //处理检修对象
        for (RepairObjects obj : repairObjects) {
            OhObject ohObject = new OhObject();
            ohObject.setEqFacId(obj.getEqFacMng().getId());//检修设备id
            String repairUserIds = "";//检修人员id
            for (SysUser user : obj.getRepairUsers()) {

                repairUserIds += user.getId() + ",";
            }
            ohObject.setOherId(repairUserIds);
            ohObject.setOhPlanDraftId(planDraft.getId());

            //添加检修对象记录
            int result = ohObjectMapper.insert(ohObject);
            if(result == 0){
                throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
            }
        }

        return true;
    }


    /**
     * 修改检修计划
     * @param ohPlanDraftDTO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public boolean patchById(OhPlanDraftDTO ohPlanDraftDTO) {

        OhPlanDraft ohPlanDraft = ohPlanDraftDTO.getOhPlanDraft();

       /* if(ohPlanDraft.getState() != 0){
            return false;
        }*/

        OhPlanDraft planDraft = new OhPlanDraft();
        BeanUtils.copyProperties(ohPlanDraft,planDraft);

        //重新设置检修人姓名
        String objectsName = "";

        List<RepairObjects> repairObjects = ohPlanDraftDTO.getRepairObjects();

        for (RepairObjects object : repairObjects) {

            List<SysUser> users = object.getRepairUsers();
            for (SysUser user : users) {
                SysUser sysUser = sysUserMapper.selectById(user.getId());
                if(sysUser != null){
                    objectsName += sysUser.getName() + ",";
                }
            }
        }

        planDraft.setObjectsName(objectsName);


        //更新检修计划
        int ret = ohPlanDraftMapper.updateById(planDraft);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        //删除处理对象
        LambdaQueryWrapper<OhObject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OhObject::getOhPlanDraftId,planDraft.getId());
        List<OhObject> list = ohObjectMapper.selectList(queryWrapper);
        for (OhObject obj : list) {
            ohObjectMapper.deleteById(obj.getId());
        }

        //重新添加处理检修对象
        for (RepairObjects obj : repairObjects) {
            OhObject ohObject = new OhObject();
            ohObject.setEqFacId(obj.getEqFacMng().getId());//检修设备id
            String repairUserIds = "";//检修人员id
            for (SysUser user : obj.getRepairUsers()) {

                repairUserIds += user.getId() + ",";
            }
            ohObject.setOherId(repairUserIds);
            ohObject.setOhPlanDraftId(planDraft.getId());

            //添加检修对象记录
            int result = ohObjectMapper.insert(ohObject);
            if(result == 0){
                throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
            }
        }

        return true;
    }

    /**
     * 根据id获取检修计划信息
     * @param id
     * @return
     */
    public OhPlanDraftVO getById(Long id) {

        //根据id查询
        OhPlanDraft planDraft = ohPlanDraftMapper.selectById(id);
        if(planDraft == null){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        OhPlanDraftVO res = new OhPlanDraftVO();
        BeanUtils.copyProperties(planDraft,res);

        SysUser creator = sysUserMapper.selectById(res.getCreator());
        res.setCreateName(creator == null ? "该用户不存在":creator.getName());

        Organization organization = organizationMapper.selectById(res.getOrgId());
        res.setOrganizationName(organization == null ? "该部门不存在": organization.getName());

        //保存检修对象list
        List<OhObjectVO> list = new ArrayList<>();

        //查询检修对象
        LambdaQueryWrapper<OhObject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OhObject::getOhPlanDraftId,res.getId());
        List<OhObject> ohObjects = ohObjectMapper.selectList(queryWrapper);

        for (OhObject obj : ohObjects) {
            OhObjectVO vo = new OhObjectVO();

            //查询设备设施
            EqFacMng eqFacMng = eqFacMngMapper.selectById(obj.getEqFacId());
            vo.setEqFacMng(eqFacMng);

            if(eqFacMng == null){
                continue;
            }

            //查询设备设施区域位置
            PositionList positionList = positionMapper.selectById(eqFacMng.getPosition());
            vo.setPositionName(positionList == null ? "该区域不存在" : positionList.getName());

            //查询管辖部门名称
            Organization organization1 = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
            vo.setDepartmentName(organization1 == null ? "该部门不存在" : organization1.getName());

            String names = "";

            String oherId = obj.getOherId();
            long[] ids = Arrays.stream(oherId.split(",")).mapToLong(Long::parseLong).toArray();
            List<Long> idList = new ArrayList<>();

            for (long i : ids) {
                SysUser user = sysUserMapper.selectById(i);
                if(user != null){
                    idList.add(i);
                    names += user.getName() + ",";
                }
            }

            vo.setRepairUserIdList(idList);
            vo.setRepairUsersName(names);
            list.add(vo);
        }

        //检修对象字段处理

        res.setOhObjectVOList(list);
        return res;
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public boolean deleteByIds(Long[] ids) {

        //删除检修计划
        for (Long id : ids) {
            int ret = ohPlanDraftMapper.deleteById(id);
            if(ret == 0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }

            //删除当前检修计划的检修对象
            LambdaQueryWrapper<OhObject> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OhObject::getOhPlanDraftId,id);
            int delete = ohObjectMapper.delete(queryWrapper);
            if(delete == 0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }
        }
        return true;
    }

    /**
     * 列表查询
     * @param ohPlanDraftQO
     * @return
     */
    public IPage<OhPlanDraftVO> getListByQO(OhPlanDraftQO ohPlanDraftQO) {
        Page<OhPlanDraftVO> page = new Page<>(ohPlanDraftQO.getCurrent(), ohPlanDraftQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<OhPlanDraftVO> list = ohPlanDraftMapper.selectByQO(page, ohPlanDraftQO);
        for (OhPlanDraftVO record : list.getRecords()) {
            Organization org = organizationMapper.selectById(record.getOrgId());
            record.setOrganizationName(org == null ? "该部门不存在" : org.getName());
            SysUser creator = sysUserMapper.selectById(record.getCreator());
            record.setCreateName(creator == null ? "该用户不存在" : creator.getName());
        }
        return list;
    }

    /**
     * 发布检修计划
     * @param id
     * @return
     */
    public Boolean issuePlan(Long id){
        OhPlanDraft planDraft = ohPlanDraftMapper.selectById(id);
        planDraft.setState(1);
        int ret = ohPlanDraftMapper.updateById(planDraft);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }
        return true;
    }
}
